/*
 * Copyright 2010 Gal Dolber.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.unnison.demo.client.login;

import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.user.client.ui.HasText;
import com.google.inject.Inject;

import com.unnison.demo.client.common.HasFocus;
import com.unnison.demo.client.common.HasInnerText;
import com.unnison.demo.client.login.LoginPresenter.LoginBinder;
import com.unnison.demo.client.main.MainPresenter;
import com.unnison.framework.client.GuitPresenter;
import com.unnison.framework.client.binder.GuitBinder;
import com.unnison.framework.client.binder.ViewField;
import com.unnison.framework.client.binder.ViewHandler;
import com.unnison.framework.client.binder.contributor.KeyCode;
import com.unnison.framework.client.binder.contributor.RunAsync;
import com.unnison.framework.client.place.Place;
import com.unnison.framework.client.place.PlaceName;

@RunAsync
@PlaceName("login")
public class LoginPresenter extends GuitPresenter<LoginBinder> implements Place<Void> {

    public interface LoginBinder extends GuitBinder<LoginPresenter> {
    }

    public static final String ERROR_LOGGIN_IN = "Error loggin in!";

    public static final String YOU_LOGGED_IN = "You logged in!";

    private final MainPresenter hasContent;

    @ViewField
    HasText username;

    @ViewField("username")
    HasFocus usernameFocus;

    @ViewField
    HasText password;

    @ViewField
    HasInnerText message;

    @Inject
    public LoginPresenter(MainPresenter hasContent) {
        this.hasContent = hasContent;
    }

    @ViewHandler
    void clear$click() {
        username.setText(null);
        password.setText(null);
        message.setInnerText(null);
        usernameFocus.setFocus(true);
    }

    @Override
    public void go(Void data) {
        hasContent.setContent(getView(), 0);
    }

    @ViewHandler
    void login$click() {
        tryLogin();
    }

    @ViewHandler
    @KeyCode({KeyCodes.KEY_ENTER})
    void login$username$password$keyPress() {
        tryLogin();
    }

    private void tryLogin() {
        if ("admin".equals(username.getText()) && "admin".equals(password.getText())) {
            message.setInnerText(YOU_LOGGED_IN);
        } else {
            message.setInnerText(ERROR_LOGGIN_IN);
        }
    }
}
